package com.example.hotfixdemo;

import android.Manifest;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import com.taobao.sophix.SophixManager;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {

    private TextView mTvTest;
    private Disposable mSubscribe;
    private boolean hasNewPatch = false;//由后台接口给出

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initPermission();
        initListener();
    }

    private void initListener() {
        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hasNewPatch = true;
                SophixManager.getInstance().queryAndLoadNewPatch();//从这里下载补丁，这里是计费的api，一天调用的次数要小于20次。这个需要后台接口控制 是否使用热修复，如果添加白名单 就可以不使用热修复
                loadUpdate();
            }
        });
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setText();
                new NewTestClass().test(MainActivity.this);
            }
        });
    }

    /**
     * 加载更新
     */
    private void loadUpdate() {
        mSubscribe = Observable.timer(30, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(aLong -> {//这个延迟时间 最好多一点，这样补丁就可能下载下来了。比如可以设置为5分钟
            if (hasNewPatch) {//isAppInBackground(this) &&
                hasNewPatch = false;
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder
                        .setTitle("更新提醒")
                        .setMessage("小老弟，有更新了，是否马上更新？")
                        .setCancelable(false)
                        .setPositiveButton("是的", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                RestartAPPTool.restartAPP(getApplicationContext(), 50);//可以弹个对话框 提示用户重启APP，用户点确定，然后重启APP 让补丁生效
                            }
                        }).show();
            }
        });
    }

    private void setText() {
        mTvTest.setText("修复热更新崩溃的问题-test2");
        mTvTest.setTextColor(Color.RED);
    }

    private void initView() {
        mTvTest = findViewById(R.id.tv_test);
    }

    private void initPermission() {
        new RxPermissions(this).request(Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(granted -> {
            if (granted) {
            } else {
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSubscribe != null) {
            mSubscribe.dispose();
        }
    }

    /**
     * APP是否运行在后台
     *
     * @param context
     * @return
     */
    public static boolean isAppInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) { // Android5.0及以后的检测方法
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                //前台程序
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }
        return isInBackground;
    }

}
